#ifndef EVENT_HTTP_CLIENT_H
#define EVENT_HTTP_CLIENT_H
#include <string>
#include <map>
#include "ConnectionHandler.h"
#include "EventDns.h"
struct event;
class EventDns;
struct bufferevent;
class Service;
class Connection;
struct http_parser;
using namespace std;
class EventHttpClient;
class EventHttpClientHandler {
public:
	virtual void onHttpClientComplete(EventHttpClient* client, int statusCode, const string& data) = 0;
};

class EventHttpClient : public ConnectionHandler, public EventDnsHandler
{
public:
	~EventHttpClient();
	static EventHttpClient* create(Service* service, const string& url, EventHttpClientHandler *handler);
	bool commit();
	void cancle();
	void* data;

	static int http_response_on_header_complete(http_parser* parser);
	static int http_response_on_message_complete(http_parser* parser);
	static int http_response_on_header_value(http_parser* parser, const char* at, size_t len);
	static int http_response_on_header_field(http_parser* parser, const char* at, size_t len);
	static int http_response_on_body(http_parser* parser, const char* at, size_t len);
	
	static void onTimeout(int fd, short event, void* args);
	void setMethod(const std::string& method);
	void addHeader(const std::string& key, const std::string& value);
	void setPostData(const std::string& data);
	void setArgs(void* args);
	void* getArgs();
private:
	void onDnsResolve(EventDns* dns, bool isSuccess, const std::string& ip);
private:
	bool ParseUrl();
private:
	void onConnected(Connection* conn);
	void onClose(Connection* conn);
	void onData(Connection* conn);
private:
	EventDns* m_dns;
	http_parser* m_parser;
	Connection* m_connection;
	Service* m_service;
	std::string m_response;
	std::string m_url;
	std::string m_scheme;
	std::string m_query;
	std::string m_host;
	std::string m_port;
	std::string m_path;
	std::string m_flagment;
	std::string m_method;
	std::string m_postData;
	bool m_isComplete;
	int m_statusCode;
	std::map<string, string> m_mapRequestHeaders;
	bool m_isTls;
	EventHttpClientHandler* m_handler;
	void* m_args;
	event* m_timeout;
};
#endif
